package cn.kt.springbootuploadmaster.controller;

import cn.kt.springbootuploadmaster.domin.FileChunkParam;
import cn.kt.springbootuploadmaster.domin.ResultVO;
import cn.kt.springbootuploadmaster.service.FileChunkService;
import cn.kt.springbootuploadmaster.service.FileService;
import cn.kt.springbootuploadmaster.service.LocalStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tao.
 * Date: 2022/6/29 11:56
 * 描述:
 */
@RestController
@Slf4j
@RequestMapping("/api")
public class FileUploadController {

    @Autowired
    private FileService fileService;
    @Autowired
    private FileChunkService fileChunkService;
    @Autowired
    private LocalStorageService localStorageService;

    @GetMapping("/upload")
    public ResultVO<Map<String, Object>> checkUpload(FileChunkParam param) {
        log.info("文件MD5:" + param.getIdentifier());
        List<FileChunkParam> list = fileChunkService.findByMd5(param.getIdentifier());
        Map<String, Object> data = new HashMap<>(1);
        // 判断文件存不存在
        if (list.size() == 0) {
            data.put("uploaded", false);
            return new ResultVO<>(200, "上传成功", data);
        }
        // 处理单文件
        if (list.get(0).getTotalChunks() == 1) {
            data.put("uploaded", true);
            data.put("url", "");
            return new ResultVO<Map<String, Object>>(200, "上传成功", data);
        }
        // 处理分片
        int[] uploadedFiles = new int[list.size()];
        int index = 0;
        for (FileChunkParam fileChunkItem : list) {
            uploadedFiles[index] = fileChunkItem.getChunkNumber();
            index++;
        }
        data.put("uploadedChunks", uploadedFiles);
        return new ResultVO<Map<String, Object>>(200, "上传成功", data);
    }

    @PostMapping("/upload")
    public ResultVO chunkUpload(FileChunkParam param) {
        log.info("上传文件：{}", param);
        boolean flag = fileService.uploadFile(param);
        if (!flag) {
            return new ResultVO(211, "上传失败");
        }
        return new ResultVO(200, "上传成功");
    }


    @GetMapping(value = "/download/{md5}/{name}")
    public void downloadbyname(HttpServletRequest request, HttpServletResponse response, @PathVariable String name, @PathVariable String md5) throws IOException {
        localStorageService.downloadByName(name, md5, request, response);
    }


}
